<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css'

import {computed, onBeforeUnmount, ref, shallowRef, watch} from 'vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import api from "@/api"
import Operate from "@/hooks/Operate"

const props = defineProps({
  /* 编辑器的内容 */
  content: {
    type: String,
    default: "",
  },
  /* 只读 */
  readonly: {
    type: Boolean,
    default: false,
  },
  // 上传文件大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  /* 高度 */
  height: {
    type: Number,
    default: 350,
  },
  /* 宽度 */
  width: {
    type: String,
    default: "",
  },
})

const emit = defineEmits([
  'update:content'
])

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

const curContent = ref<string>('')

const mode = 'default'

const styles = computed(() => {
  let style: any = {}
  // if (props.minHeight) {
  //   style.minHeight = `${props.minHeight}px`
  // }
  if (props.width) {
    style.width = `${props.width}`
  }
  return style
})

watch(() => props.content, (val) => {
  if (val !== curContent.value) {
    curContent.value = val ? val : ""
  }
}, {immediate: true})

watch(() => curContent.value, (val) => {
  emit("update:content", val)
}, {immediate: true})

const toolbarConfig = {
  excludeKeys: [
    "uploadVideo"
  ]
}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      // 自定义上传
      async customUpload(file: File, insertFn: any) {
        if (!handleBeforeUpload(file)) {
          return
        }
        const formData = new FormData()
        formData.append('file', file)
        formData.append('busType', '36')

        api.uploadFile(formData).then(resp => {
          const data = resp.data.data
          const url = data.fileUrl  + "|||" + data.uuid
          const alt = ""
          const href = ""
          insertFn(url, alt, href)
        }).catch((error) => {
          imgUploadError()
          console.error('上传图片失败', error)
        })
      }
    }
  }
}

// 上传前校检格式和大小
function handleBeforeUpload(file): boolean {
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize
    if (!isLt) {
      Operate.error(`上传文件大小不能超过 ${props.fileSize} MB!`)
      return false
    }
  }
  return true
}

function imgUploadError(): void {
  Operate.error("上传图片失败")
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) {
    return
  }
  editor.destroy()
})

const handleCreated = (editor) => {
  // 记录 editor 实例，重要！
  editorRef.value = editor
}
</script>

<template>
  <div class="editor-w" style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 500px; overflow-y: hidden;"
      v-model="curContent"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>

<style scoped lang="less">
.editor-w {
}
</style>
